<template>
  <view>
    <!-- 注册成为志愿者的组件 -->
    <view class="topnav">
      <span>首页</span>->注册志愿
    </view>
    <!-- 上传的表单盒子 -->
    <view class="contentBox">
      <view class="topic"> 请完成身份信息录入</view>
      <u--form labelPosition="left" :model="model1" :rules="rules" ref="userRef" labelWidth="100px">
        <u-form-item label="姓名:" prop="userInfo.name" borderBottom>
          <u--input v-model="model1.userInfo.name" border="none"></u--input>
        </u-form-item>
        <u-form-item label="性别:" prop="userInfo.sex" borderBottom @click="showSex = true">
          <u--input v-model="model1.userInfo.sex" disabled disabledColor="#ffffff" placeholder="请选择性别" border="none">
          </u--input>
          <u-icon slot="right" name="arrow-right"></u-icon>
        </u-form-item>
        
        <u-form-item label="年龄:" prop="userInfo.age" borderBottom>
          <u--input v-model="model1.userInfo.age" border="none" placeholder="请填写你的年龄"></u--input>
        </u-form-item>

        <u-form-item label="联系方式:" prop="userInfo.phone" borderBottom>
          <u--input v-model="model1.userInfo.phone" border="none" placeholder="请填写移动号码"></u--input>
        </u-form-item>

      </u--form>
      <u-action-sheet :show="showSex" :actions="actions" title="请选择性别" description="如果选择保密会报错" @close="showSex = false"
        @select="sexSelect">
      </u-action-sheet>
      <!-- 上传身份证照片 -->
      <view class="indentity-box">
          <span>上传身份证正面：</span>
          <view class="container-indentity">
            <view class="indentity-picture">
              <u-upload :fileList="fileList6" @afterRead="afterRead" @delete="deletePic" name="6" multiple :maxCount="1"
                width="250" height="150">
                <image  class="indentity-img" src="https://cdn.uviewui.com/uview/demo/upload/positive.png" mode="widthFix"
                  style="width: 250px;height: 150px;"></image>
              </u-upload>
            </view>
          </view>     
      </view>
      <!-- 上传近期免冠照 -->
      <view class="selfPicture-box">
        <span>请上传近期一寸免冠照：</span>
        <view class="self-picture">
          <view class="container-selfPicture">
            <u-upload
            	:fileList="fileList5"
            	@afterRead="afterRead"
            	@delete="deletePic"
            	name="5"
            	multiple
            	:maxCount="1"
            ></u-upload>
          </view>
        </view>
      </view>
      <!-- 提示信息 -->
      <view class="tips">
        提交信息后将会在2个工作日以内审核您的信息
      </view>
      <!-- 提交信息 -->
      <view class="btn">
        <button type="primary" text="确定" @click="saveVolunteer">提交</button>
      </view>
      
      <!-- 去登录 -->
      <view class="login">
        <navigator url="/subpkg/loginVolunteer/loginVolunteer">去登录</navigator>
      </view>
    </view>
  </view>
</template>

<script>
  import { mapMutations ,mapState} from "vuex"
  export default {
    name: "BecomeVolunteer",
    data() {
      return {
        showSex: false,
        model1: {
          userInfo: {
            name: '',
            sex: '',
            phone: "",
            age:''
          },
        },
        actions: [{
            name: '男',
          },
          {
            name: '女',
          },
          {
            name: '保密',
          },
        ],
        rules: {
          'userInfo.name': {
            type: 'string',
            required: true,
            message: '请填写姓名',
            trigger: ['blur', 'change']
          },
          'userInfo.sex': {
            type: 'string',
            max: 1,
            required: true,
            message: '请选择男或女',
            trigger: ['blur', 'change']
   		     },
           'userInfo.age': {
             type: 'string',
             required: true,
             message: '请填写年龄',
             trigger: ['blur', 'change']
           },
           'userInfo.phone': {
             type: 'string',
             required: true,
             message: '请填写电话',
             trigger: ['blur', 'change']
           },

        },
        radio: '',
        switchVal: false,
        //身份证照片存放容器
        fileList6: [],
        // 存放免冠照
        fileList5:[]
      };
    },
    computed:{
      ...mapState('m_volunteer',['volunteerInfo'])
    },
    methods: {
      ...mapMutations('m_volunteer',["updateVolunteerInfo","updateToken_v"]),
      // 新增用户
      saveVolunteer(){
       this.$refs.userRef.validate().then(async res=>{
         // 验证通过，发起注册请求
         // 将登录者的信息存进vuex便于后面自动登录判断
          const {data:result} = await uni.$http.post('/volunteers',this.model1.userInfo);
          // console.log(result)
          if (result.code!==200) return uni.$u.toast("用户存在")
          uni.$showMsg(result.msg)
          // this.updateVolunteerInfo(this.model1.userInfo)
          // 发起登录请求
         // this.getlogin()
         // 清空表单
         this.model1.userInfo = {}
       }).catch(errors => {
				uni.$u.toast('校验失败')
			})
      },
      // 发起登录请求
      async getlogin(){
        const {data:res} = await uni.$http.get('/volunteers/'+this.volunteerInfo.name+'/'+this.volunteerInfo.phone)
        console.log(res)
        if(res.code!==200) return uni.$u.toast('请退出再进入')
        this.updateToken(res.token)
        this.updateVolunteerInfo(res.data)
      },
      
      // 性别选择的处理函数
      sexSelect(e) {
        this.model1.userInfo.sex = e.name
        this.$refs.userRef.validateField('userInfo.sex')
      },
      // 新增图片
      			async afterRead(event) {
      				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      				let lists = [].concat(event.file)
      				let fileListLen = this[`fileList${event.name}`].length
      				lists.map((item) => {
      					this[`fileList${event.name}`].push({
      						...item,
      						status: 'uploading',
      						message: '上传中'
      					})
      				})
      				for (let i = 0; i < lists.length; i++) {
      					const result = await this.uploadFilePromise(lists[i].url)//调用另一个方法
      					let item = this[`fileList${event.name}`][fileListLen]
      					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
      						status: 'success',
      						message: '',
      						url: result
      					}))
      					fileListLen++
      				}
      			},
    },
    onReady() {
      //如果有自定义的方法校验规则需要使用这个方法解决兼容问题
      // this.$refs.userRef.setRules(this.rules)
    },
  }
</script>

<style lang="scss">
  .topnav {
    span {
      font-weight: 800;
    }
    height: 20px;
    line-height: 20px;
    padding: 5px 0 0 5px;
  }
  .contentBox {
    .topic {
      text-align: center;
    }
    box-sizing: border-box;
    padding: 10px;
  }
  .indentity-box{
    margin-top: 10px;
    .container-indentity{
      margin-top: 10px;
      width: 100%;
      display: flex;
      justify-content: center;
      .indentity-picture{
        width: 250px;
        height: 150px;
      }
    }
    }
  .selfPicture-box{
    margin-top: 10px;
    .self-picture{
      width: 100%;
      margin-top: 10px;
      display: flex;
      justify-content: center;
      .container-selfPicture{
        height: 80px;
        width: 80px;
      }
    }
  }
  .tips{
    margin-top: 10px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    background-color: #909399;
    color:white;
    border-radius: 3px;
    font-size: 12px;
  }
  .btn{
    margin-top: 10px;
  }
  .login{
    text-align:center;
    color:blue;
  }
</style>
